<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\CategoryModel;
use app\model\QuotesModel;
use app\model\RedisModel;
use think\App;
use think\facade\Db;

class Quotes extends Base {

    protected $middleware = [Auth::class];
    private $model;

    public $cacheKey="quotes:id:";

    public $dayCacheKey="quotes:day:";

    private $req;

    private $page;

    private $limit;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 999999;

        $this->model = new QuotesModel();

        $this->isLogin();
    }

    /*
     * 获取店铺列表
     * */
    public function getList(){

        $where =[];
        if(!empty($this->req["category_pid"])){
            $where["category_pid"] = $this->req["category_pid"];
        }

        $list = $this->model->getList($where,$this->page,$this->limit,["date"=>"DESC"]);

        $total = $this->model->getTotal($where);

        return $this->succData($total,$list);

    }


    /*
     * 添加
     * */
    public function add()
    {
        if(!isset($this->req['content']) || empty($this->req['content'])){
            return $this->fail("内容不能为空");
        }


        $res = $this->model->insertGetId([
            "content"=>$this->req['content'],
            "date"=>isset($this->req['date']) ? $this->req['date'] : null,
        ]);

        if(!empty($date)){
            $this->delDayCache($this->req['date']);
        }


        if($res){
            return $this->succ();
        }else{
            return $this->fail();
        }
    }



    public function del()
    {
        if(!isset($this->req['quotes_id']) || empty($this->req['quotes_id'])){
            return $this->fail("请选择要删除的每日一修");
        }

        $res = $this->model->where("quotes_id",$this->req['courseMenusModel'])->delete();
        if($res){
            $this->delCache($this->req['quotes_id']);
            return $this->succ();
        }else{
            return $this->fail();
        }
    }


    public function delDayCache($day)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->dayCacheKey.$day);
    }

    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}
